
/**
 * 
 * @author Guillermo Mendez-Kestler
 * @author Patrick Ramsey
 *
 */
import java.io.Serializable;
import java.net.InetAddress;

public class Client {

	/**
	 * @param args
	 */
	
	private String IP;// holds the IP of another node in the ring
	private int port;//holds the port of another node in the ring
	private Node localNode;//reference to the localNode that is created when we call create Node.
	private boolean debug;//boolean to say whether debug statements are on or not.
	
	public Client()
	{
		debug = true;
	}
	
	public static void main(String[] args) {
		Client myClient = new Client();
		myClient.cmdLine(args);
		
	}
	
	/**
	 * This method creates a Node with the local host ip and port
	 */
	private void createNode()
	{
		try{
			localNode = new Node(InetAddress.getLocalHost(), Node.DEFAULT_PORT);
		}
		catch(Exception e)
		{
			System.err.println(e);
		}
		
	}
	
	/**
	 * This method checks for command line arguments to create a new ring or join an existing one
	 * @param args
	 */
	private void cmdLine(String[] args)
	{
		if(args.length > 0)
		{
			debug("In ring already created");
			//joins the ring at the entry point provided
			this.createNode();
			debug("after createNode call");
			IP = args[0];
			port = Integer.parseInt(args[1]);
			localNode.joinRing(IP, port);
		}
		else
		{
			debug("In ring not created");
			//start a new ring
			this.createNode();
			localNode.joinRing();
		}
	}
	/**
	 * This method looks up a key starting on the localNode
	 * @param key
	 * @return
	 */
	public Object lookup(String key) {
		Object returned = null;
		try{
			returned = localNode.lookup(key,InetAddress.getLocalHost()+":"+Node.DEFAULT_PORT);
		}
		catch(Exception e)
		{
			System.err.println(e);
		}
		debug("Returned is: " + localNode.GetLookupReturn());
		if(returned == null)
			System.out.println("Sorry could not be found");
		return returned;
	}
	/**
	 * This method puts on object on the ring starting from the localNode
	 * @param key
	 * @param value
	 */
	public void put (String key, Serializable value){
		localNode.addObject(key, value);
	}
	
	private void debug(String msg)
	{
		if(debug)
			System.out.println(msg);
	}

}